import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { VitePWA } from 'vite-plugin-pwa';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

function setupPlugins(env) {
  return [
    vue(),
    env.VITE_GLOB_APP_PWA === 'true' &&
      VitePWA({
        injectRegister: 'auto',
        manifest: {
          name: 'chatGPT',
          short_name: 'chatGPT',
          icons: [
            { src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
            { src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' }
          ]
        }
      }),
    createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      // 指定 symbolId 格式
      symbolId: 'icon-[name]'
    })
  ].filter(Boolean); // 过滤掉 falsy 值
}

export default defineConfig(({ mode }) => {
  const viteEnv = loadEnv(mode, process.cwd());

  return {
    base: '/wechat/',
    resolve: {
      alias: {
        '@': path.resolve(process.cwd(), 'src')
      }
    },
    plugins: setupPlugins(viteEnv),
    server: {
      host: '0.0.0.0',
      port: 1002,
      open: false,
      proxy: {
        '/wechatapi': {
          target: viteEnv.VITE_APP_API_BASE_URL,
          changeOrigin: true, // 允许跨域
          rewrite: (path) => path.replace('/wechatapi/', '/')
        },
        '/uploads': {
          target: viteEnv.VITE_APP_API_BASE_URL,
          changeOrigin: true // 允许跨域
          //rewrite: path => path.replace('/api/', '/'),
        },
        '/openapi': {
          target: viteEnv.VITE_APP_API_BASE_URL,
          changeOrigin: true // 允许跨域
          //rewrite: path => path.replace('/api/', '/'),
        }
      }
    },
    build: {
      reportCompressedSize: false,
      sourcemap: false,
      commonjsOptions: {
        ignoreTryCatch: false
      }
    },
    // 禁用 ESLint
    esbuild: {
      drop: ['console', 'debugger']
    },
    optimizeDeps: {
      esbuildOptions: {
        target: 'es2020'
      }
    }
  };
});
